package io.github.shenbinglife.springboot2.layui.admin.controller;

import io.github.shenbinglife.springboot2.layui.admin.entity.Menu;
import io.github.shenbinglife.springboot2.layui.admin.service.impl.MenuService;
import io.github.shenbinglife.springboot2.layui.common.model.Result;
import io.github.shenbinglife.springboot2.layui.common.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * MenuController
 *
 * @author shenbing
 * @date 2021/4/12 21:26
 */
@RestController
@RequestMapping("admin/menus")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 查询菜单子树
     * @param id    菜单ID
     * @param recursive
     * @return
     */
    @GetMapping("{id}/tree")
    public Result<List<TreeNode<Long>>> getMenuTree(@PathVariable Long id, @RequestParam(defaultValue = "true") Boolean recursive) {
        List<TreeNode<Long>> menuTree = menuService.getMenuTree(id, recursive);
        return Result.success(menuTree);
    }

    /**
     * 根据ID获取菜单
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result<Menu> getMenu(@PathVariable Long id) {
        return menuService.getOptionalById(id)
                .map(Result::success)
                .orElse(Result.failure("菜单不存在"));
    }

    /**
     * 更新菜单
     * @param menu
     * @return
     */
    @PostMapping()
    public Result<Menu> update(@RequestBody Menu menu) {
        menuService.update(menu);
        return Result.success(menuService.getById(menu.getId()));
    }

    /**
     * 创建菜单
     * @param menu
     * @return
     */
    @PutMapping
    public Result<Menu> create(@RequestBody Menu menu) {
        Menu save = menuService.save(menu);
        return Result.success(save);
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result<Void> delete(@PathVariable Long id) {
        menuService.deleteWithChildren(id);
        return Result.success();
    }
}
